package cn.wqb.bpp.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerificationCodeUtils {

    public static String createCodeImgAndAddToSession(HttpServletRequest request, String sessionKey) {
        int width = 90;
        int height = 31;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.getGraphics();
        Color c = new Color(255, 255, 255);
        g.setColor(c);
        g.fillRect(0, 0, width, height);//画一个外框
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index] + "", (i * 15) + 3, 18);//画随机字符
            sb.append(ch[index]);
        }
        String checkCode = sb.toString();
        request.getSession().setAttribute(sessionKey, checkCode);
        String base64 = ImageUtils.bufferedImageToBase64(bufferedImage);
        return base64;
    }

}
